package com.oktest.measure.kt

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import com.allen.library.helper.ShapeBuilder
import com.cali.libcore.util.UIUtils
import com.chad.library.adapter.base.entity.node.BaseNode
import com.oktest.measure.entity.Type

/**
 * @Author hhh
 * @Date 2020/9/27
 */

fun View.setDrawable(color: Int, dp: Float) {
    val context = this.context
    val colorRes = ContextCompat.getColor(context, color)
    ShapeBuilder()
        .setShapeType(ShapeBuilder.RECTANGLE)
        .setShapeSolidColor(colorRes)
        .setShapeStrokeColor(colorRes)
        .setShapeStrokeWidth(0)
        .setShapeCornersRadius(UIUtils.dip2px(this.context, dp).toFloat())
        .into(this)
}


fun ImageView.setArrowSpin(data: BaseNode, isAnimate: Boolean) {
    val entity = data as Type
    if (entity.isExpanded) {
        if (isAnimate) {
            this.rotation(90f)
        } else {
            this.rotation = 90f
        }
    } else {
        if (isAnimate) {
            this.rotation(0f)
        } else {
            this.rotation = 0f
        }
    }
}

fun ImageView.rotation(value: Float) {
    ViewCompat.animate(this).setDuration(200)
        .setInterpolator(DecelerateInterpolator())
        .rotation(value)
        .start()
}

fun Context.getBitmap(vectorDrawableId: Int): Bitmap? {
    val context = this
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
        val vectorDrawable: Drawable? = ContextCompat.getDrawable(context,vectorDrawableId)
        vectorDrawable?.apply {
            val bitmap = Bitmap.createBitmap(
                vectorDrawable.intrinsicWidth,
                vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(bitmap)
            vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
            vectorDrawable.draw(canvas)
            return bitmap
        }
        return null
    } else {
        return BitmapFactory.decodeResource(context.resources, vectorDrawableId)
    }
}